const app = getApp();
import {
  animation
} from '../../utils/SliderNumber'
import {
  getPhoneByCode,
  recordsGetTotal,
  recordsPage,
  unLoginRecordsPage,
  recordsUpdateExchange,
  updatePoints,
  recordslist
} from "../../utils/api/index";
import {
  getWarpText,
  roundedRect
} from '../../utils/util'
import Wxml2Canvas from '../../components/Wxml2Canvas/index';
Page({
  timer: null, // 定时器
  drawImage1: null, // 
  ffCanvas: null, // 
  totalPage: 1,

  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    dataList: [],
    userPointList: [],
    userPointListStr: '',
    totalPointsObj: {
      totalPoints: 0,
      exchangeNum: 0,
    }, // 总积分
    exchangeThing: {}, // 总积分对应商品
    isLoading: true,
    isSkeletonLoading: true, //显示骨架屏
    isLogin: false, // 是否登录
    islikeShow: false, // 是否显示等价交换弹框
    isqueryShow: false, // 是否查询弹框
    islogsShow: false, // 是否查询弹框
    isShearShow: false, // 是否查询弹框
    rowObj: {},
    thingName: '',
    unit: '',
    price: '',
    pointsNumber: '',
    shareImgUrl: '',
  },

  // 获取我的积分值
  getPoints() {
    recordsGetTotal().then(res => {
      this.setData({
        ['totalPointsObj.exchangeNum']: res.data.exchangeNum,
        exchangeThing: res.data.exchangeThing,
      }, () => {
        this.drawImage()
      })
      animation(200, this.data.totalPointsObj.totalPoints, res.data.totalPoints, (val) => {
        this.setData({
          ['totalPointsObj.totalPoints']: parseInt(val),
        })
      })
    }).catch(err => {

    })
  },
  // 获取列表
  async getList() {
    this.setData({
      isLoading: true
    })
    let params = {
      pageNum: this.data.pageNum,
      pageSize: 10,
    }
    let res
    if (this.data.isLogin) {
      res = await recordsPage(params);
    } else {
      res = await unLoginRecordsPage(params)
    }
    let list = res.data.records.map(item => {
      return item
    });
    list = this.data.dataList.concat(list);
    this.setData({
      dataList: list,
      isLoading: false,
      isSkeletonLoading: false,
    })
    this.totalPage = res.data.pages;
    wx.stopPullDownRefresh();
    this.getrecordslist();
  },
  // 获取已获得的积分列表
  getrecordslist() {
    recordslist().then(res => {
      let userPointListStr = ''
      res.data.forEach((item, index) => {
        if (index + 1 < res.data.length) {
          userPointListStr += item.platformName + '、'
        } else {
          userPointListStr += item.platformName
        }
      })
      this.setData({
        userPointList: res.data,
        userPointListStr: userPointListStr,
      }, () => {
        this.drawImage()
      })
    }).catch(err => {
      this.setData({
        userPointList: [],
        userPointListStr: ''
      })
    })
  },
  // 查询
  queryMsg(e) {
    const {
      item
    } = e.currentTarget.dataset;
    if (item.queryType === 0) {
      // 跳转到小程序
      wx.navigateToMiniProgram({
        appId: item.appId,
        path: item.appPath,
        envVersion: 'trial', //develop 开发版本 trial体验版 release 正式版
        success(res) {
          // 打开成功
        }
      })
    } else {
      this.setData({
        isqueryShow: true,
        rowObj: {
          ...item
        }
      })
    }
  },
  // 记录
  recordsMsg(e) {
    const {
      item
    } = e.currentTarget.dataset;
    this.setData({
      islogsShow: true,
      rowObj: {
        ...item
      }
    })
  },
  // 点击手机号验证
  getphonenumber(e) {
    const {
      code
    } = e.detail;
    if (code) {
      wx.showLoading({
        title: '请稍后...',
        mask: true,
        success: async () => {
          let {
            openId
          } = wx.getStorageSync('userInfo')
          let params = {
            code,
            openId: openId
          }
          getPhoneByCode(params).then((res) => {
            const data = res.data;
            wx.setStorageSync('token', data.accessToken);
            wx.setStorageSync('userInfo', data);
            app.setGlobalData('userInfo', data);
            wx.hideLoading();
            wx.showToast({
              title: '授权成功',
              duration: 2500,
              icon: "none"
            })
          }).catch(err => {

          });
        }
      })
    } else {
      wx.showToast({
        title: '授权失败',
        duration: 2500,
        icon: "none"
      })
    }
  },
  // 点击触发交换等交互
  exchangeGoods() {
    this.setData({
      islikeShow: true
    })
  },
  // 交换物提交
  formSubmit(e) {
    let {
      price,
      thingName,
      unit
    } = e.detail.value;
    if (!thingName) {
      wx.showToast({
        title: '请输入喜欢的物品名称',
        icon: "none"
      })
      return
    }
    if (!unit) {
      wx.showToast({
        title: '请输入物品单位',
        icon: "none"
      })
      return
    }
    if (!/^[1-9]\d*$/.test(price)) {
      wx.showToast({
        title: '请填写正整数！',
        icon: "none"
      })
      return
    }
    if (!price) {
      wx.showToast({
        title: '请输入单价',
        icon: "none"
      })
      return
    }
    let params = {
      price,
      thingName,
      unit
    }
    recordsUpdateExchange(params).then(res => {
      wx.showToast({
        title: '修改成功',
        duration: 2500,
        icon: "none"
      })
      this.getPoints();
      this.formReset();

    }).catch(err => {

    })
  },
  formReset() {
    this.setData({
      islikeShow: false,
      thingName: '',
      unit: '',
      price: '',
    })
  },
  // 更换积分
  pointformSubmit(e) {
    let {
      pointsNumber
    } = e.detail.value;
    const {
      id
    } = this.data.rowObj;
    if (!/^[1-9]\d*$/.test(pointsNumber)) {
      wx.showToast({
        title: '请填写正整数！',
        icon: "none"
      })
      return
    }
    if (pointsNumber <= 0) {
      wx.showToast({
        title: '请填写积分值！',
        icon: "none"
      })
      return
    }
    let params = {
      platformId: id,
      pointsNumber
    }
    updatePoints(params).then(res => {
      wx.showToast({
        title: '提交成功',
        duration: 2500,
        icon: "none"
      })
      this.setData({
        dataList: [],
        pageNum: 1,
        pointsNumber: ''
      })
      this.totalPage = 1;
      this.getList();
      this.getPoints();
      this.pointformReset();
    }).catch(err => {

    })
  },
  pointformReset() {
    this.closeDialog()
  },
  // 显示分享
  showShear() {
    this.setData({
      isShearShow: true
    })
  },
  // 关闭弹框
  closeDialog() {
    this.setData({
      islikeShow: false, // 是否显示等价交换弹框
      isqueryShow: false, // 是否查询弹框
      islogsShow: false,
      isShearShow: false,
    }, () => {
      this.timer = setTimeout(() => {
        this.setData({
          rowObj: {},
        })
      }, 500);
    })
  },


  // 保存图片到相册
  async saveImage() {
    // 创建离屏 2D canvas 实例
    const canvas = wx.createOffscreenCanvas({
      type: '2d',
      width: 718,
      height: 832
    })
    const context = canvas.getContext('2d')
    // 创建一个图片
    const image = canvas.createImage();
    context.clearRect(0, 0, 718, 832)
    // 等待图片加载
    await new Promise(resolve => {
      image.src = '/images/share-bg.png';
      image.onload = resolve
    })
    context.drawImage(image, 0, 0, 718, 832);
    const {
      userPointList,
      totalPointsObj, // 总积分
      exchangeThing, // 总积分对应商品
    } = this.data;
    let text = '我有'
    context.fillStyle = "#804431";
    context.font = "bold 36px Arial";
    getWarpText(context, text, 70, 112, 640, 58, 1)
    let text1 = `${totalPointsObj.totalPoints}积分`
    context.fillStyle = "#FA5622";
    context.font = "bold 46px Arial";
    getWarpText(context, text1, 70, 170, 640, 58, 1)
    let text2 = '散落在各平台，相当于'
    context.fillStyle = "#804431";
    context.font = "bold 36px Arial";
    getWarpText(context, text2, 70, 218, 640, 58, 1)
    let text3 = `${totalPointsObj.exchangeNum}`
    context.fillStyle = "#FA5622";
    context.font = "bold 46px Arial";
    getWarpText(context, text3, 70, 278, 640, 58, 1)
    let text4 = `${exchangeThing.unit?exchangeThing.unit:'瓶'}${exchangeThing.thingName?exchangeThing.thingName:'可乐'}。`
    context.fillStyle = "#804431";
    context.font = "bold 36px Arial";
    getWarpText(context, text4, 70, 326, 640, 58, 1)
    let text5 = '积分来自'
    context.fillStyle = "#804431";
    context.font = "bold 28px Arial";
    getWarpText(context, text5, 294, 380, 240, 58, 1)

    // 积分来自
    userPointList.forEach((item, index) => {
      if (index === 0) {
        roundedRect(context, 72, 424, 178, 60, 30, "#FFBC17")
        context.fillStyle = "#362D23";
        context.font = "bold 24px Arial";
        getWarpText(context, item.platformName, 110, 464, 124, 60, 1)
      }
      if (index === 1) {
        roundedRect(context, 272, 424, 178, 60, 30, "#FFBC17")
        context.fillStyle = "#362D23";
        context.font = "bold 24px Arial";
        getWarpText(context, item.platformName, 310, 464, 124, 60, 1)
      }
      if (index === 2) {
        roundedRect(context, 474, 424, 178, 60, 30, "#FFBC17")
        context.fillStyle = "#362D23";
        context.font = "bold 24px Arial";
        getWarpText(context, item.platformName, 512, 464, 124, 60, 1)
      }
      if (index === 3) {
        roundedRect(context, 72, 504, 178, 60, 30, "#FFBC17")
        context.fillStyle = "#362D23";
        context.font = "bold 24px Arial";
        getWarpText(context, item.platformName, 110, 544, 124, 60, 1)
      }
      if (index === 4) {
        roundedRect(context, 272, 504, 178, 60, 30, "#FFBC17")
        context.fillStyle = "#362D23";
        context.font = "bold 24px Arial";
        getWarpText(context, item.platformName, 310, 544, 124, 60, 1)
      }
      if (index === 5) {
        roundedRect(context, 474, 504, 178, 60, 30, "#FFBC17")
        context.fillStyle = "#362D23";
        context.font = "bold 24px Arial";
        getWarpText(context, "等......", 512, 544, 124, 60, 1)
      }
    })
    this.ffCanvas = canvas;
    // 获取画完后的数据
    const imgData = context.canvas.toDataURL('image/png');
    // 获取用户相册授权
    const _that = this;
    wx.getSetting({
      success(res) {
        // 如果已授权
        if (res.authSetting['scope.writePhotosAlbum']) {
          _that.onSaveImage(imgData)
          // 如果没有授权 
        } else if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
          // 调起用户授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              _that.onSaveImage(imgData)
            },
            fail() {
              wx.showToast({
                title: '您没有授权，无法保存到相册',
                icon: 'none'
              })
            }
          })
          // 如果之前授权已拒绝
        } else {
          wx.openSetting({
            success(res) {
              if (res.authSetting['scope.writePhotosAlbum']) {
                _that.onSaveImage(imgData)
              } else {
                wx.showToast({
                  title: '您没有授权，无法保存到相册',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },
  // 生成图片
  onSaveImage(imgData) {
    const _this = this;
    const fs = wx.getFileSystemManager();
    const number = new Date().getTime();
    const imgFilePath = wx.env.USER_DATA_PATH + '/' + number + '.png'
    fs.writeFile({
      filePath: imgFilePath, //设置下载图片的地址
      data: imgData.slice(22), //slice(22)的目的是去掉data:image/png;base64
      encoding: 'base64',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: imgFilePath, //设置下载图片的地址
          success: (res) => {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: () => {
            wx.showToast({
              title: '保存到相册失败',
            })
          }
        })
      }
    })
  },

  drawImage() {
    let _this = this;
    this.drawImage1 = new Wxml2Canvas({
      width: 375, // 宽， 以iphone6为基准，传具体数值，其他机型自动适配
      height: 300, // 高
      element: 'canvas1',
      background: '#f0f0f0',
      progress(percent) {},
      finish(url) {
        _this.setData({
          shareImgUrl: url
        })
      },
      error(err) {
        console.log(err, 'err')
      }
    });

    let data = {
      list: [{
        type: 'wxml',
        limit: '.share__canvas', // 限定绘制元素的范围，取指定元素与它的相对位置
        class: '.share__canvas .draw_canvas',
        x: 0,
        y: 0
      }]
    }
    this.drawImage1.draw(data);
  },

  /**
   * 生命周期函数--监听页面加载
   * 
   */
  onLoad: function (options) {
    let isLogin = app.getToken();
    this.setData({
      isLogin: isLogin,
      dataList: [],
      pageNum: 1,
    })
    this.totalPage = 1;
    if (isLogin) {
      this.getPoints();
    }
    this.getFirstList()

    app.watch("userInfo", () => {
      let isLogin = app.getToken();
      this.setData({
        isLogin: isLogin,
        pageNum: 1,
      }, () => {
        this.totalPage = 1;
        if (isLogin) {
          this.getPoints();
        }
        this.getFirstList()
      })
    })
  },

  // 解决初始化页面跳动bug  
  async getFirstList() {
    let isLogin = app.getToken();
    let params = {
      pageNum: 1,
      pageSize: 10,
    }
    let res
    if (isLogin) {
      res = await recordsPage(params);
    } else {
      res = await unLoginRecordsPage(params);
    }
    this.setData({
      dataList: res.data.records,
      isLoading: false,
      isSkeletonLoading: false,
    })
    this.totalPage = res.data.pages;
    this.getrecordslist()
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      dataList: [],
      pageNum: 1,
    })
    this.totalPage = 1;
    if (this.data.isLogin) {
      this.getPoints();
    }
    this.getList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoading) {
      return
    }
    let totalPage = this.totalPage;
    let pageNum = this.data.pageNum;
    if (pageNum < totalPage) {
      pageNum++
      this.setData({
        pageNum
      })
      this.getList();
    }
  },
  onUnload() {
    this.ffCanvas = null;
    clearTimeout(this.timer);
    this.timer = null;
    this.drawImage1 = null;
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const {
      shareImgUrl,
      isLogin,
      totalPointsObj
    } = this.data;
    let imageUrl = '/images/share-card-Login.png'
    if (isLogin && totalPointsObj.totalPoints > 0) imageUrl = shareImgUrl
    return {
      title: '看看您的积分值多少？',
      path: '/pages/home/index',
      imageUrl: imageUrl
    }
  }
})